#pragma once
#include<iostream>
#include<jsoncpp/json/json.h>
#include<algorithm>
#include"index.hpp"
#include"util.hpp"
#include"log.hpp"


struct InvertedPrintelem
{
    int doc_id;
    int weight;
    std::vector<std::string> words;
    InvertedPrintelem():doc_id(0),weight(0)
    {}
};

class Search
{
private:
    Index *index;

private:
    const std::string GetDesc(const std::string& word,const std::string& content)
    {
        int pos=content.find(word);
        int begin_=(pos-50)>=0?pos-50:0;
        int end_=(pos+100)<content.size()?pos+word.size()+100:content.size()-1;
        std::string desc(content,begin_,end_-begin_+1);
        desc+="...";
        return desc;
    }  
public:
    void InitiaSearch()
    {
        //建立索引
        //构建index对象
        index=Index::GetInstance();
        //构建索引
        index->Build_Index();
    }

    void search(const std::string& keyword,std::string* json_result)
    {
        //1、将keyword分词
        //std::cout<<"搜索中"<<std::endl;
        LOG(NORMAL,"搜索中");
        std::vector<std::string> words; 
        util::JiebaUtil::CutString(keyword,&words);
        //2、根据关键字进行倒排索引，得到doc_id
        std::vector<InvertedPrintelem> Inverted_List_all;
        //用来去重
        std::unordered_map<int,InvertedPrintelem> tokens_map;
        for(auto& word:words)
        {
            boost::to_lower(word);
            InvertedList* Inverted_list=index->Get_Invert_Index(word);
            if(Inverted_list==nullptr)
            {
                //std::cout<<"none"<<std::endl;
                LOG(WARNING,"查找倒排错误");
                continue;
            }
            //进行去重
            for(auto& elem:*Inverted_list)
            {
                auto& item=tokens_map[elem.doc_id];
                item.doc_id=elem.doc_id;
                item.weight+=elem.weight;
                item.words.push_back(elem.word);
            }
        }
        for(auto& elem:tokens_map)
        {
            Inverted_List_all.push_back(std::move(elem.second));
        }
        //Inverted_List_all.insert(Inverted_List_all.end(),Inverted_list->begin(),Inverted_list->end());

        // 3、将索引结果整合、排序
        std::sort(Inverted_List_all.begin(), Inverted_List_all.end(),
                  [](const InvertedPrintelem &e1, const InvertedPrintelem &e2)
                  { return e1.weight > e2.weight; });
        // 4、将内容摘要,构建json串
        Json::Value root;
        for (auto &elem : Inverted_List_all)
        {
            Json::Value tmp;
            DocInfo *doc = index->Get_Forward_Index(elem.doc_id);
            tmp["title"] = doc->title;
            tmp["description"] = GetDesc(elem.words[0], doc->content);
            tmp["url"] = doc->url;
            tmp["weight"] = elem.weight;
            tmp["doc_id"]=elem.doc_id;
            root.append(tmp);
        }
        Json::StyledWriter fw;
        *json_result = fw.write(root);

    }
};